﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class MeetingsReport : Form
    {
        public MeetingsReport()
        {
            InitializeComponent();
        }

        int regID, avpID, year, kv;

        private void MeetingsReport_Load(object sender, EventArgs e)
        {
            cbYear.Items.Clear();
            for (int i = 1991; i < 2101; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = -1;

            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 0; i < 4; i++)
            {
                cbKvartal.Items.Add((i + 1).ToString() + " Квартал");
            }
            cbKvartal.SelectedIndex = 0;

        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            regID = 0;
            if (cbRegion.SelectedIndex >= 0)
            {
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;

                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.DisplayMember = "Name";
                cbAVP.ValueMember = "ID";
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            avpID = 0;
            if (cbAVP.SelectedIndex >= 0)
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
        }


        private void chbRegion_CheckedChanged(object sender, EventArgs e)
        {
            cbRegion.Enabled = chbRegion.Checked;
        }

        private void chbAVP_CheckedChanged(object sender, EventArgs e)
        {
            cbAVP.Enabled = chbAVP.Checked;
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            year = 0;
            if (cbYear.SelectedIndex >= 0)
                Int32.TryParse(cbYear.Text, out year);
        }

        private void cbKvartal_SelectedIndexChanged(object sender, EventArgs e)
        {
            kv = cbKvartal.SelectedIndex;
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbYear.Enabled = chbYear.Checked;
            if (!chbYear.Checked)
                chbKvartal.Checked = false;
        }

        private void chbKvartal_CheckedChanged(object sender, EventArgs e)
        {
            if (chbYear.Checked)
                cbKvartal.Enabled = chbKvartal.Checked;
            else
                chbKvartal.Checked = cbKvartal.Enabled = false;
        }

        private void chbVisits_CheckedChanged(object sender, EventArgs e)
        {
            tbVisits.Enabled = chbVisits.Checked;
        }

        private void buttonShowReport_Click(object sender, EventArgs e)
        {
            int? rID, aID, y, k, vis;

            if (chbRegion.Checked && regID > 0)
                rID = regID;
            else
                rID = null;

            if (chbAVP.Checked && avpID > 0)
                aID = avpID;
            else
                aID = null;

            if (chbYear.Checked && year > 0)
                y = year;
            else
                y = null;

            if (chbKvartal.Checked && kv >= 0)
                k = kv + 1;
            else
                k = null;

            int v;
            Int32.TryParse(tbVisits.Text, out v);
            if (chbVisits.Checked && v > 0)
                vis = v;
            else
                vis = null;

            dgvMeetings.DataSource = DBClass.RESPContext.MeetingsCounts(rID, aID, y, k, vis);

            if (InformationClass.Lang)
            {
                dgvMeetings.Columns["RegionID"].HeaderText = "Район";
                dgvMeetings.Columns["Name"].HeaderText = "АВП";
                dgvMeetings.Columns["PlanMeetingQuantity"].HeaderText = "Количество собраний по плану";
                dgvMeetings.Columns["CountMeetings"].HeaderText = "Количество собраний по факту";
                dgvMeetings.Columns["VisCount"].HeaderText = "Количество посещений";
            }
            else
            {
                dgvMeetings.Columns["RegionID"].HeaderText = "Туман номи";
                dgvMeetings.Columns["Name"].HeaderText = "СИУ номи";
                dgvMeetings.Columns["PlanMeetingQuantity"].HeaderText = "Режа бўйича йиғилишлар сони";
                dgvMeetings.Columns["CountMeetings"].HeaderText = "Амалда ўтказилган йиғилишлар сони";
                dgvMeetings.Columns["VisCount"].HeaderText = "Ташрифлар сони";
            }
            for (int i = 0; i < dgvMeetings.RowCount; i++)
            {
                dgvMeetings.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }

            dgvMeetings.AutoResizeColumns();

        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;
        Workbooks excelappworkbooks;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvMeetings.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                
                excelworksheet.Select(1);
                excelapp.Visible = true;
            }
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i3r2.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i3r2uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbYear.Checked)
                excelworksheet.Cells[6, 2] = "Период: __ квартал "+cbYear.Text+" года";
            if (chbKvartal.Checked)
                excelworksheet.Cells[6, 2] = "Период: "+cbKvartal.Text+" " + cbYear.Text + " года";
            if (chbRegion.Checked)
                excelworksheet.Cells[4, 3] = cbRegion.Text;

            for (int i = 0; i < dgvMeetings.Rows.Count; i++)
            {
                for (int j = 1; j < dgvMeetings.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + 9, dgvMeetings.Columns[j].DisplayIndex + 2] = dgvMeetings[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + 9, dgvMeetings.Columns[j].DisplayIndex + 2]);
                }

                excelworksheet.Cells[i + 9, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + 9, 2]);
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Rows.AutoFit();
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void dgvMeetings_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvMeetings.Columns.Contains("RegionID"))
            {
                if (e.ColumnIndex.Equals(dgvMeetings.Columns["RegionID"].Index) && e.Value != null)
                {
                    e.Value = DBClass.Regions.Where(wh => wh.ID == (int)e.Value).Select(se => se.Name).FirstOrDefault();
                }
            }
            if (dgvMeetings.Columns.Contains("VisCount"))
            {
                if (e.ColumnIndex.Equals(dgvMeetings.Columns["VisCount"].Index) && e.Value == null)
                {
                    e.Value = 0;
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvMeetings.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvMeetings);
        }
    }
}
